package com.shuyu.web.controller.platform;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuyu.common.core.controller.BaseController;
import com.shuyu.common.core.domain.AjaxResult;
import com.shuyu.common.core.page.TableDataInfo;
import com.shuyu.common.enums.OperationType;
import com.shuyu.common.exception.ServiceException;
import com.shuyu.common.utils.StringUtils;
import com.shuyu.domain.*;
import com.shuyu.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 授权登录相关
 * 
 * @author
 */
@RestController
@RequestMapping("/platform/activity")
@Api(tags = "活动管理")
public class PActivityController extends BaseController
{
    @Resource
    private ActivityService activityService;
    @Resource
    private ActivityProductService activityProductService;
    @Resource
    private ActivityCollectCardService activityCollectCardService;
    @Resource
    private ApprovalProcessDetailService approvalProcessDetailService;
    @Resource
    private ActivityTmpService activityTmpService;
    @Resource
    private ActivityProductTmpService activityProductTmpService;
    @Resource
    private ActivityCollectCardTmpService activityCollectCardTmpService;



    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/list")
    @ApiOperation("查询活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "name", value = "活动名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "活动类型  1：集卡消卡；2：转盘；3：促销活动；4：积分活动 ", dataType = "Integer", dataTypeClass = Integer.class)
    })
    public TableDataInfo list(String startTime,String endTime, String name, Integer type)
    {
        startPage();
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<Activity>()
                .eq(ObjectUtil.isNotNull(type),Activity::getType,type)
                .like(StringUtils.isNotEmpty(name),Activity::getName, name)
                .eq(Activity::getDelFlag,0);
        if(StringUtils.isNotEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
            queryWrapper.not(Wrapper->Wrapper.lt(Activity::getEndTime,startTime).or().gt(Activity::getStartTime,endTime));
        }else if(StringUtils.isNotEmpty(startTime)&&StringUtils.isEmpty(endTime)){
            queryWrapper.ge(Activity::getEndTime,startTime);
        }else if(StringUtils.isNotEmpty(endTime)&&StringUtils.isEmpty(startTime)){
            queryWrapper.le(Activity::getStartTime,endTime);
        }
        List<Activity> list = activityService.list(queryWrapper);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('system:activity:add')")
    @PostMapping
    @ApiOperation("添加活动")
    public AjaxResult add(@RequestBody Activity activity){
        activity.setCreateTime(new Date());
        activity.setAuditStatus(0);
        activity.setStatus(1);
        activity.setOperationType(OperationType.上架.type);
        activityService.save(activity);
        addList(activity);
        approvalProcessDetailService.createApprovalProcess(2, OperationType.上架.type,activity.getId());
        return AjaxResult.success();
    }
    private void checkAuditStatus(int activityId){
        int count = activityService.count(new LambdaQueryWrapper<Activity>().eq(Activity::getAuditStatus, 0).eq(Activity::getId, activityId));
        if(count>0){
            throw new ServiceException("审核未完成，不允许再去发起审核");
        }
    }
    @PreAuthorize("@ss.hasPermi('system:activity:update')")
    @PutMapping
    @ApiOperation("修改活动")
    public AjaxResult update(@RequestBody ActivityTmp activity){
        int activityId = activity.getId();
        checkAuditStatus(activityId);
        activity.setCreateTime(new Date());
        activity.setAId(activityId);
        activity.setId(null);
        activityTmpService.remove(new LambdaUpdateWrapper<ActivityTmp>().eq(ActivityTmp::getAId,activityId));
        activityTmpService.save(activity);
        editList(activity);
        approvalProcessDetailService.createApprovalProcess(2, OperationType.修改.type,activityId);

        Activity act = new Activity();
        act.setAuditStatus(0);
        act.setId(activityId);
        act.setOperationType(OperationType.修改.type);
        activityService.updateById(act);
        return AjaxResult.success();
    }
    @PutMapping("/updateStatus")
    @ApiOperation("修改上下架状态")
    public AjaxResult updateStatus(@RequestBody Activity activity){
        checkAuditStatus(activity.getId());
        Activity act = new Activity();
        if(activity.getStatus()==0){
            act.setOperationType(OperationType.上架.type);
            approvalProcessDetailService.createApprovalProcess(2, OperationType.上架.type,activity.getId());
        }else if(activity.getStatus()==1) {
            act.setOperationType(OperationType.下架.type);
            approvalProcessDetailService.createApprovalProcess(2, OperationType.下架.type,activity.getId());
        }
        act.setAuditStatus(0);
        act.setId(activity.getId());
        activityService.updateById(act);
        return AjaxResult.success();
    }
    @GetMapping("/{id}")
    @ApiOperation("获取活动详情")
    public AjaxResult detail(@PathVariable int id){
        Activity activity = activityService.getById(id);
        List<ActivityProduct> activityProductList = activityProductService.getProductListByActivityId(id);
        activity.setActivityProductList(activityProductList);
        AjaxResult ajax = AjaxResult.success(activity);
        if(activity.getAuditStatus()==0&&activity.getOperationType()==OperationType.修改.type){
            ActivityTmp activityTmp = activityTmpService.getOne(new LambdaQueryWrapper<ActivityTmp>().eq(ActivityTmp::getAId,id).last("limit 1"));
            List<ActivityProductTmp> activityProductTmpList = activityProductTmpService.getProductListByActivityId(activityTmp);
            activityTmp.setActivityProductList(activityProductTmpList);
            ajax.put("dataEx", activityTmp);
        }
        return ajax;
    }

    @PreAuthorize("@ss.hasPermi('system:activity:del')")
    @PutMapping("/{id}")
    @ApiOperation("删除活动")
    public AjaxResult del(@PathVariable int id){
        checkAuditStatus(id);
        activityProductService.remove(new LambdaUpdateWrapper<ActivityProduct>().eq(ActivityProduct::getActivityId,id));
        approvalProcessDetailService.createApprovalProcess(2, OperationType.删除.type,id);
        Activity act = new Activity();
        act.setAuditStatus(0);
        act.setId(id);
        act.setOperationType(OperationType.删除.type);
        return toAjax(activityService.updateById(act));
    }

    private void  addList(Activity activity){
        activityProductService.remove(new LambdaUpdateWrapper<ActivityProduct>().eq(ActivityProduct::getActivityId,activity.getId()));
        for (ActivityProduct activityProduct : activity.getActivityProductList()) {
            activityProduct.setActivityId(activity.getId());
            activityProduct.setActivityType(activity.getType());
            activityProduct.setCreateTime(new Date());
            activityProductService.save(activityProduct);
            if(activity.getType()==1){// 1：集卡消卡；
                List<ActivityCollectCard> activityCollectCardList = activityProduct.getActivityCollectCardList();
                for (ActivityCollectCard activityCollectCard : activityCollectCardList) {
                    activityCollectCard.setActivityProductId(activityProduct.getId());
                }
                activityCollectCardService.saveBatch(activityCollectCardList);
            }
        }
    }
    private void  editList(ActivityTmp activity){
        activityProductTmpService.remove(new LambdaUpdateWrapper<ActivityProductTmp>().eq(ActivityProductTmp::getAId,activity.getAId()));
        activityCollectCardTmpService.remove(new LambdaUpdateWrapper<ActivityCollectCardTmp>().eq(ActivityCollectCardTmp::getAId,activity.getAId()));
        for (ActivityProductTmp activityProduct : activity.getActivityProductList()) {
            activityProduct.setActivityId(activity.getId());
            activityProduct.setActivityType(activity.getType());
            activityProduct.setCreateTime(new Date());
            activityProduct.setAId(activity.getAId());
            activityProductTmpService.save(activityProduct);
            if(activity.getType()==1){// 1：集卡消卡；
                List<ActivityCollectCardTmp> activityCollectCardList = activityProduct.getActivityCollectCardList();
                for (ActivityCollectCardTmp activityCollectCard : activityCollectCardList) {
                    activityCollectCard.setActivityProductId(activityProduct.getId());
                    activityCollectCard.setAId(activity.getAId());
                }
                activityCollectCardTmpService.saveBatch(activityCollectCardList);
            }
        }
    }

    @GetMapping("/productList/{activityId}")
    @ApiOperation("查询活动下面产品列表")
    public AjaxResult productList(@PathVariable int activityId)
    {
        List<ActivityProduct> list = activityProductService.getProductListByActivityId(activityId);
        return AjaxResult.success(list);
    }

}
